﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Reflection.Emit;
using System.Reflection;

namespace Fabs.Net.GIL
{
    public class Executable
    {

        public Executable()
        {
            Classes = new List<Class>();
        }

        public string Name { get; set; }
        public string FileName { get; set; }

        public List<Class> Classes { get; set; }

        public ModuleBuilder Output { get; private set; }
        private AssemblyBuilder Builder { get; set; }
        

        public bool IsCompiled { get; private set; }
        public bool HasEntryPoint { get; private set; }
        public MethodInfo EntryPoint { get; private set; }

        public void Compile()
        {
            AppDomain currentDomain = Thread.GetDomain();
            AssemblyName assemblyName = new AssemblyName();
            assemblyName.Name = Name;
            if (string.IsNullOrEmpty(FileName))
            {
                FileName = Name + ".exe";
            }

            Builder = currentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
            Output = Builder.DefineDynamicModule(FileName, FileName);

            foreach (Class c in Classes)
            {
                c.Compile(this);
                if (!HasEntryPoint)
                {
                    if (c.HasEntryPoint)
                    {
                        Builder.SetEntryPoint(c.EntryPoint);
                        HasEntryPoint = true;
                        EntryPoint = c.EntryPoint;
                    }
                }
            }

            IsCompiled = true;
        }

        public void Save()
        {
            if (IsCompiled)
            {
                if (HasEntryPoint)
                {
                    Builder.Save(FileName);
                }
                else
                {
                    throw new Exception("Başlangıç methodu tanımlanmamış");
                }
            }
            else
            {
                Compile();
                Save();
            }
        }
    }
}